from datetime import datetime
import pytz
from typing import List
import pandas as pd
from core.models import Order # Import ORM Order model
from adapters.platform_interface import PlatformAdapter
from utils.multiplier import get_multiplier

class TradingViewAdapter(PlatformAdapter):
    """TradingView平台适配器"""
    
    def __init__(self):
        self.beijing_tz = pytz.timezone('Asia/Shanghai')
        self.chicago_tz = pytz.timezone('America/Chicago')
    
    def convert_to_orders(self, raw_data: pd.DataFrame) -> List[Order]:
        """将TradingView导出的数据转换为标准订单格式"""
        orders = []
        for _, row in raw_data.iterrows():
            # 转换时间字段
            open_time = self._convert_time(row['open_time'])
            close_time = self._convert_time(row['close_time'])
            expiration = self._convert_time(row['expiration']) if pd.notna(row['expiration']) else None
            
            # 转换数值字段为float (SQLAlchemy Float Column)
            # 注意：这里直接将原始的数值数据转换为float，因为SQLAlchemy的Column(Float)接收float
            quantity = float(row['quantity']) if pd.notna(row['quantity']) else None
            filled = float(row['filled']) if pd.notna(row['filled']) else None
            quantity_left = float(row['quantity']) - float(row['filled']) if pd.notna(row['quantity']) and pd.notna(row['filled']) else None
            limit_price = float(row['limit_price']) if pd.notna(row['limit_price']) else None
            stop_price = float(row['stop_price']) if pd.notna(row['stop_price']) else None
            avg_fill_price = float(row['avg_fill_price']) if pd.notna(row['avg_fill_price']) else None
            commission = float(row['commission']) if pd.notna(row['commission']) else None
            multiplier = float(row['multiplier']) if pd.notna(row['multiplier']) else None
            
            order = Order()
            order.order_id = str(row['order_id'])
            order.symbol = str(row['symbol'])
            order.side = str(row['side'])
            order.order_type = str(row['order_type'])
            order.quantity = quantity
            order.filled = filled
            order.quantity_left = quantity_left
            order.limit_price = limit_price
            order.stop_price = stop_price
            order.avg_fill_price = avg_fill_price
            order.status = str(row['status'])
            order.open_time = open_time
            order.close_time = close_time
            order.duration = str(row['duration'])
            order.commission = commission
            order.expiration = expiration
            order.multiplier = multiplier
            orders.append(order)
        return orders
    
    def _convert_time(self, time_val) -> datetime:
        """转换时间字符串为datetime对象"""
        if pd.isna(time_val):
            return None
            
        if isinstance(time_val, pd.Timestamp):
            if time_val.tzinfo is None:
                return time_val.tz_localize(self.beijing_tz)
            return time_val
            
        if isinstance(time_val, datetime):
            if time_val.tzinfo is None:
                return self.beijing_tz.localize(time_val)
            return time_val
            
        # 尝试不同的日期格式
        formats = [
            '%Y/%m/%d %H:%M',      # 2025/6/20 14:30
            '%Y/%m/%d %H:%M:%S',   # 2025/6/20 14:30:00
            '%Y-%m-%d %H:%M:%S',   # 2025-6-20 14:30:00
            '%Y-%m-%d %H:%M',      # 2025-6-20 14:30
            '%Y/%m/%d',            # 2025/6/20
            '%Y-%m-%d',            # 2025-6-20
            '%m/%d/%Y %H:%M',      # 6/20/2025 14:30
            '%m/%d/%Y %H:%M:%S',   # 6/20/2025 14:30:00
            '%m/%d/%Y',            # 6/20/2025
            '%d/%m/%Y %H:%M',      # 20/6/2025 14:30
            '%d/%m/%Y %H:%M:%S',   # 20/6/2025 14:30:00
            '%d/%m/%Y'             # 20/6/2025
        ]
        
        # 如果只有日期没有时间，添加默认时间 00:00:00
        if len(str(time_val).split()) == 1:
            time_val = f"{time_val} 00:00:00"
            
        for fmt in formats:
            try:
                dt = datetime.strptime(time_val, fmt)
                dt = self.beijing_tz.localize(dt)
                return dt
            except ValueError:
                continue
                
        raise ValueError(f"无法解析时间格式: {time_val}")

    def get_symbol_multiplier(self, symbol: str) -> float:
        """获取品种的乘数"""
        base_symbol = symbol[:-3] if len(symbol) > 3 else symbol
        return get_multiplier(base_symbol)
    
    def get_session(self, dt: datetime) -> str:
        """根据时间判断交易时段"""
        chicago_time = dt.astimezone(self.chicago_tz)
        hour = chicago_time.hour
        return 'RTH' if 8 <= hour < 15 else 'ETH' 